const Article = require("../model/article");
const User = require("../model/system/User");
const JWT = require("../util/jwt");
const config = require("../config/config");
// 创建文章
exports.createArticle = async (req, res, next) => {
  try {
    const article = new Article({
      ...req.body,
    });
    article.author = req.user._id;
    // ♥ 映射 显示作者信息
    await article.populate("author");
    await article.save();
    res.status(200).json({
      code: 200,
      message: "保存成功",
      data: article,
    });
  } catch (error) {
    next(error);
  }
};

// 获取文章列表
exports.getArticles = async (req, res, next) => {
  try {
    const { pageNumber = 0, pageSize = 10, tag, author } = req.query;
    let filter = {};
    if (tag) {
      filter.tagList = tag;
    }
    if (author) {
      const user = await User.findOne({ username: author });
      filter.author = user ? user._id : null;
    }
    const articles = await Article.find(filter)
      .skip(pageNumber * pageSize)
      .limit(pageSize)
      .sort({
        createdAt: -1, // 按创建时间倒序
      }) // 按创建时间倒序
      .populate("author");
    const count = await Article.countDocuments();
    res.status(201).json({
      code: 200,
      message: "成功",
      data: {
        list: articles,
        pageNumber: pageNumber,
        pageSize: pageSize,
        tatil: count
      },
    });
  } catch (error) {
    next(error);
  }
};
// 获取文章详情
exports.getArticlesDetail = async (req, res, next) => {
  try {
    const article = await Article.findById(req.params.id).populate("author");
    if (!article) {
      return res.status(404).json({
        code: 404,
        message: "文章不存在",
      });
    }
    res.status(201).json({
      code: 200,
      message: "成功",
      data: article,
    });
  } catch (error) {
    next(error);
  }
};

// 修改文章
exports.updateArticles = async (req, res, next) => {
  try {
    const article = req.article;
    const bodyArticle = req.body.article;
    console.log(bodyArticle, "bodyArticle");
    article.title = bodyArticle.title || article.title;
    article.content = bodyArticle.content || article.content;
    article.tagList = bodyArticle.tagList || article.tagList;
    article.description = bodyArticle.description || article.description
    article.body = bodyArticle.body || article.body

    await article.save();
    res.status(200).json({
      code: 200,
      message: "修改成功",
      data: article,
    });
  } catch (error) {
    next(error);
  }
};
// 删除文章
exports.deleteArticles = async (req, res, next) => {
  try {
    console.log(req.article,"req.article")
    await req.article.deleteOne();
    res.status(200).json(
      {
        code: 200,
        message: "删除成功",
      }
    )
  } catch (error) {
    next(error);
  }
};